import { vitalConfigProvideKey } from 'vital';
import { MciButton, MciForm, MciFormItem, MciMessageBox, MciTag } from '@/components/base';
import { useApprovalProvide } from '@/components/business/Approval/index';
import * as i18n from '@/locales';
import { useDrawerStore } from '@/components/base/Drawer/store';
import './index.scss';
import { MciRichEditor } from '@/components/complex';
import { approvalDateFormat } from '../Progress/list/item';
import { PropType } from 'vue';
import { TApprovalComment } from '@/components/business/Approval/approval-helper';
import { postWorkflowApprovalProcessCommentCreate, IPostWorkflowApprovalProcessCommentCreateReq } from '@/api';
import { FormRulesMap } from 'element-plus/es/components/form/src/form.type';
import { ElFormContext } from 'element-plus';
import { getUserIdList } from '@/components/complex/RichEditor/components/Mention/useMention';

export const ApprovalCommentForm = defineComponent({
  name: 'ApprovalComment',
  props: {
    // 只有回复功能
    static: {
      type: Boolean,
      default: false
    },
    maxEditorHeight: {
      type: String,
      default: '300px'
    }
  },
  emits: ['cancel'],
  setup(props, { emit }) {
    const formRef = ref(null as TNullable<ElFormContext>);
    const editorRef = ref(null as TNullable<InstanceType<typeof MciRichEditor>>);
    const drawerStore = useDrawerStore();

    const { getApprovalProgress, processInstanceId, businessKey } = useApprovalProvide();

    const formModel = reactive({
      comment: ''
    });
    const rules = reactive<FormRulesMap>({
      comment: [{ required: true, message: i18n.t('请输入评论'), trigger: 'blur' }]
    });
    provide(vitalConfigProvideKey, { formMode: 'edit' });
    const userData = ref(null as any);

    // 回复
    const setReply = (user: TApprovalComment) => {
      userData.value = user;
      const { userId, userName } = user.owner || {};
      const { addMention, clearContent } = editorRef.value || {};
      clearContent?.();
      addMention?.({ label: userName || '', value: userId!, isReply: true });
    };
    const handleCancel = () => {
      emit('cancel');
    };
    // 确认发送
    const handleReply = async () => {
      const { comment = '' } = formModel;
      const { id, owner } = userData.value || {};
      const userId = owner?.userId || '';
      const params: IPostWorkflowApprovalProcessCommentCreateReq = {
        businessKey: businessKey.value + '',
        processInstanceId: processInstanceId.value,
        replyContent: comment
      };
      const ids = getUserIdList(comment);
      if (userData.value) {
        params.replyRecordId = ids.includes(userId) ? id : '';
      }
      params.repliedUserId = ids;
      await postWorkflowApprovalProcessCommentCreate(params);
      formRef.value?.reset();
      editorRef.value?.clearContent();
      // 重新查询数据
      getApprovalProgress();
      drawerStore.changeModify(false);
      if (!props.static) {
        handleCancel();
      }
    };

    return {
      rules,
      formRef,
      formModel,
      editorRef,
      drawerStore,
      handleCancel,
      setReply,
      handleReply
    };
  },
  render() {
    const { $t, formRef, handleReply, handleCancel } = this;

    const showDialog = async () => {
      await formRef?.validate((valid) => {
        if (valid) {
          MciMessageBox.confirm(i18n.t('确认发布吗？'), i18n.t('提示'), {
            requestLoading() {
              return handleReply();
            }
          });
        }
      });
    };

    const PublicBtn = (
      <MciButton type="primary" size="small" onClick={showDialog}>
        {$t('发布')}
      </MciButton>
    );

    const renderBtnList = () => {
      if (this.static) {
        return <div class="flex justify-end">{PublicBtn}</div>;
      }
      return (
        <div class={`grid grid-cols-2 mt-8px`}>
          {PublicBtn}
          <MciButton size="small" onClick={handleCancel}>
            {$t('取消')}
          </MciButton>
        </div>
      );
    };
    return (
      <div class="mt-12px approval-comment small">
        <MciForm class="clear-right mt-16px" ref="formRef" label-position="top" model={this.formModel} rules={this.rules}>
          <MciFormItem label={$t('评论')} prop="comment">
            <MciRichEditor
              v-model={this.formModel.comment}
              placeholder={$t('请输入评论内容,提及人员使用') + '@'}
              mention
              update-selection
              maxHeight={this.maxEditorHeight}
              class="mt-4px"
              ref="editorRef"
              onChange={() => {
                this.drawerStore.changeModify(true);
              }}
            />
          </MciFormItem>
        </MciForm>
        {renderBtnList()}
      </div>
    );
  }
});

// 评论列表
export const ApprovalCommentList = defineComponent({
  name: 'ApprovalCommentList',
  props: {
    isDefault: {
      type: Boolean,
      default: true
    },
    showReplyBtn: {
      type: Boolean,
      default: true
    },
    list: {
      type: Array as PropType<TApprovalComment[]>,
      default: () => []
    }
  },
  emits: ['comment'],
  setup(props, { emit }) {
    const { isApprovalUser, isSubmitUser } = useApprovalProvide();

    const isHandler = computed(() => {
      if (!props.showReplyBtn) return false;
      return isApprovalUser.value || isSubmitUser.value;
    });
    const onComment = (user: any) => {
      emit('comment', user);
    };
    return {
      isHandler,
      onComment
    };
  },
  render() {
    const { $t, onComment } = this;
    const renderBtn = (data: TApprovalComment) => {
      if (this.isHandler) {
        return (
          <span class="cr-green-6 cursor-pointer" onClick={() => onComment(data)}>
            {$t('回复')}
          </span>
        );
      }
    };
    const createComment = (data: TApprovalComment) => {
      const { replyContent, owner, createdTime = '' } = data;
      const { userName } = owner || {};
      return (
        <>
          <div class="text-value-12 mt-16px">{userName}</div>
          <MciRichEditor modelValue={replyContent} ellipsis={3} mode="view" class="p-8px bg-grey-1 m-y-4px" />
          <div class="text-label-12 flex justify-between">
            <span>{approvalDateFormat(createdTime)}</span>
            {renderBtn(data)}
          </div>
        </>
      );
    };

    // 缺省
    if (!this.list?.length) {
      if (!this.isDefault) return null;
      return (
        <>
          <div class="text-value-14_bold">{$t('评论')}</div>
          <div class="text-label-12 flex flex-col  items-center justify-center mt-16px bd-dashed p-16 rounded-4">
            <span class="mci-icon-inbox text-20px mb-4px"></span>
            <div>{this.$t('暂无数据')}</div>
          </div>
        </>
      );
    }

    return (
      <div class="relative">
        <div class="text-value-14_bold sticky top-0 left-0 bg-white z-1000 pb-8px">
          <span>{$t('评论')}</span>
          <MciTag class="ml-4px">{this.list.length}</MciTag>
        </div>
        {this.list.map(createComment)}
      </div>
    );
  }
});
